package com.mygdx.game.desktop.demo;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.objects.TiledMapTileMapObject;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;

/**
 * 地图
 *
 * @author Administrator
 */
public class MapTestGame extends Game {

    private static final float CAMERA_SPEED = 100.0f;

    private OrthographicCamera camera;    // 相机
    private Viewport viewport;

    private TiledMap map;
    private TmxMapLoader loader;
    private OrthogonalTiledMapRenderer renderer;

    private Vector2 direction;

    private SpriteBatch batch;
    private Array<Sprite> triggers;

    @Override
    public void create() {

        camera = new OrthographicCamera(/*1000, 1000*/);    // 控制它来观察游戏世界
        // 设置镜头的宽和高的单位
        camera.setToOrtho(false, 1024, 512);

        viewport = new FitViewport(1024, 512, camera);

        loader = new TmxMapLoader();
        map = loader.load("map/firstMap/map.tmx");

// 		资源管理器
//		assetManager.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver()));
//		assetManager.load("data/map/map.tmx", TiledMap.class);

        // 根据地图信息生成一个正投射图块地图绘制对象
        renderer = new OrthogonalTiledMapRenderer(map);

        direction = new Vector2();
        //getObjects();

        batch = new SpriteBatch();
        processMapMetadata();
    }

    public void render() {
        Gdx.gl.glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        updateCamera();

        renderer.setView(camera);
        renderer.render();
        batch.begin();
        for (Sprite trigger : triggers) {
            trigger.draw(batch);
        }
        batch.end();
    }

    public void dispose() {
        map.dispose();
        renderer.dispose();
        batch.dispose();
    }

    private void updateCamera() {
        direction.set(0.0f, 0.0f);

        int mouseX = Gdx.input.getX();
        int mouseY = Gdx.input.getY();
        int width = Gdx.graphics.getWidth();
        int height = Gdx.graphics.getHeight();

        if (Gdx.input.isKeyPressed(Input.Keys.LEFT) || (Gdx.input.isTouched() && mouseX < width * 0.25f)) {
            direction.x = -1;
        } else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || (Gdx.input.isTouched() && mouseX > width * 0.75f)) {
            direction.x = 1;
        }

        if (Gdx.input.isKeyPressed(Input.Keys.UP) || (Gdx.input.isTouched() && mouseY < height * 0.25f)) {
            direction.y = 1;
        } else if (Gdx.input.isKeyPressed(Input.Keys.DOWN) || (Gdx.input.isTouched() && mouseY > height * 0.75f)) {
            direction.y = -1;
        }

        direction.nor().scl(CAMERA_SPEED * Gdx.graphics.getDeltaTime());

        //System.out.println("direction.x:" + direction.x + ",camera.position.x:" + camera.position.x);
        camera.position.x += direction.x;

        camera.position.y += direction.y;
        // 获取map的第一个layer
        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(0);

        float cameraMinX = viewport.getWorldWidth() * 0.5f;
        float cameraMinY = viewport.getWorldHeight() * 0.5f;
        float cameraMaxX = layer.getWidth() * layer.getTileWidth() - cameraMinX;
        float cameraMaxY = layer.getHeight() * layer.getTileHeight() - cameraMinY;

        // 判断x轴出界
        camera.position.x = MathUtils.clamp(camera.position.x, cameraMinX, cameraMaxX);
        camera.position.y = MathUtils.clamp(camera.position.y, cameraMinY, cameraMaxY);

        camera.update();
    }

    public void getObjects() {
        for (MapLayer ml : map.getLayers()) {
            System.out.println(ml.getName());
            for (MapObject mo : ml.getObjects()) {//遍历对象
                if ("text".equals(mo.getName())) {
                    float x = (float) mo.getProperties().get("x");
                    float y = viewport.getWorldHeight() - (float) mo.getProperties().get("y");
                    System.out.println("x:" + x + ",y:" + y);
                }
            }
        }
    }


    private void processMapMetadata() {
        // Load entities
        System.out.println("Searching for game entities...\n");
        triggers = new Array<>();
        MapObjects objects = map.getLayers().get("object1").getObjects();
        for (MapObject object : objects) {
            String name = object.getName();
            if (name != null && name.equals("text")) {
                System.out.println("object name:" + name);
                TiledMapTileMapObject rectangleObject = (TiledMapTileMapObject) object;

                TextureRegion textureRegion = rectangleObject.getTextureRegion();
                System.out.println("Objectfound- textureRegion: " + textureRegion);

                MapProperties mapProperties = object.getProperties();
                int id = (Integer) mapProperties.get("gid");
                System.out.println("Objectfound- gid: " + id);
                Rectangle rectangle = new Rectangle();
                rectangle.setX(Float.parseFloat(mapProperties.get("x").toString()));
                float y = Float.parseFloat(mapProperties.get("y").toString());
                rectangle.setY(y);
                rectangle.setWidth(Float.parseFloat(mapProperties.get("width").toString()));
                float height = Float.parseFloat(mapProperties.get("height").toString());
                rectangle.setHeight(height);

                System.out.println("Objectfound- y: " + y + " heght:" + height);

                System.out.println("Objectfound- name: " + name);

                Sprite trigger = new Sprite(textureRegion);
                //trigger.setColor(1.0f, 1.0f, 1.0f, 0.5f);
                //trigger.setScale(rectangle.width, rectangle.height);
                trigger.setPosition(rectangle.x, rectangle.y + height);
                triggers.add(trigger);
            }
        }
    }

    public static void main(String[] args) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.width = 1024;
        config.height = 512;
        new LwjglApplication(new MapTestGame(), config);

    }
}
